package com.ship.core;

import com.google.gson.Gson;
import com.ship.entity.dto.JsonResult;
import com.ship.entity.dto.ResultCode;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.nio.file.AccessDeniedException;

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    private Logger logger = LoggerFactory.getLogger(GlobalDefaultExceptionHandler.class);

    @ExceptionHandler(value = Exception.class)
    public void defaultException(HttpServletRequest request, Exception e, HttpServletResponse response){
        logger.error("全局异常{}",e);
        String msg = "";
        if(e instanceof AccessDeniedException) {
            msg= "拒绝访问";
        }else if(e instanceof BadCredentialsException) {
            msg = "密码错误";
        }else{
            msg = e.getMessage();
        }
        JsonResult result = new JsonResult(ResultCode.EXCEPTION, msg, null);
        Gson gson = new Gson();
        String json = gson.toJson(result);
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json; charset=utf-8");
        PrintWriter out = null;
        try {
            out = response.getWriter();
            out.append(json);
            logger.info("[全局异常返回]{}", json);
        } catch (Exception e2) {
            e2.printStackTrace();
        } finally {
            if (out != null) {
                out.close();
            }
        }
    }

}
